package com.rtu.service.impl;

import com.rtu.dao.IRtuDao;
import com.rtu.dto.QueryReportDto;
import com.rtu.dto.QueryRtuDto;
import com.rtu.dto.QuerySiphonDto;
import com.rtu.dto.RtuDto;
import com.rtu.dto.SiphonDto;
import com.rtu.dto.YearSiphonDto;
import com.rtu.service.IRtuService;
import com.rtu.utils.DateUtil;
import org.apache.commons.collections.map.HashedMap;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;

import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.lang.*;

/**
 * Created by ljf on 2018/4/15.
 */
@Service
public class RtuServiceImpl implements IRtuService {
    private static final Logger logger = LoggerFactory.getLogger(RtuServiceImpl.class);
    @Resource
    private IRtuDao rtuDao;

    @Override  
    public Map query(QueryRtuDto dto) {
        Map map = new HashedMap();
        List<RtuDto> list = new ArrayList<RtuDto>();
        if (StringUtils.isNotBlank(dto.getBeginTime())) {
            dto.setBeginTime(dto.getBeginTime() + " 00:00:00");
        }
        if (StringUtils.isNotBlank(dto.getEndTime())) {
            dto.setEndTime(dto.getEndTime() + " 23:59:59");
        }

        Integer count = rtuDao.count(dto);
        if (count == 0) {
            map.put("totalPage",0);
            map.put("totalCount",0);

        } else {
            int totalPage = (count % dto.getPageRowCount() == 0) ? count / dto.getPageRowCount() : count / dto.getPageRowCount() + 1;
            dto.setStart((dto.getPage() - 1) * dto.getPageRowCount());
            list = rtuDao.query(dto);
            map.put("totalPage",totalPage);
            map.put("totalCount",count);
        }
        map.put("pageRowCount", dto.getPageRowCount());
        map.put("page",dto.getPage());
        map.put("list",list);

        return map;
    }

    @Override
    public List<RtuDto> queryRecent(QueryRtuDto dto) {
        return rtuDao.queryRecent(dto);
    }

    public IRtuDao getRtuDao() {
        return rtuDao;
    }

    public void setRtuDao(IRtuDao rtuDao) {
        this.rtuDao = rtuDao;
    }

    /**
     * 天数<=7 查所有
     * 天数>7&&天数<=30   查每天第一条数据
     * 天数>30&&天数<=180  查每周第一条数据
     * 天数>180  查每月第一条数据
     * @param dto
     * @return
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override
    public Map queryDataForReport(QueryReportDto dto) {
        //判断时间跨度
        List<RtuDto> list0 = new ArrayList<>();
        List<RtuDto> list1 = new ArrayList<>();
        Date date1 = DateUtil.parseDate(dto.getBeginTime());
        Date date2 = DateUtil.parseDate(dto.getEndTime());
        int count = DateUtil.getBetweenDays(date1,date2).intValue();
        if (count <=7 ) {
            if (StringUtils.isBlank(dto.getCh())) {
                dto.setCh("0");
                list0 = rtuDao.queryReport1(dto);
                dto.setCh("1");
                list1 = rtuDao.queryReport1(dto);
            } else {
                if ("0".equals(dto.getCh())) {
                    list0 = rtuDao.queryReport1(dto);
                } else if ("1".equals(dto.getCh())) {
                    list1 = rtuDao.queryReport1(dto);
                }
            }
        } else if (count <=30 ) {
            if (StringUtils.isBlank(dto.getCh())) {
                dto.setCh("0");
                list0 = rtuDao.queryReport2(dto);
                dto.setCh("1");
                list1 = rtuDao.queryReport2(dto);
            } else {
                if ("0".equals(dto.getCh())) {
                    list0 = rtuDao.queryReport2(dto);
                } else if ("1".equals(dto.getCh())) {
                    list1 = rtuDao.queryReport2(dto);
                }
            }
        } else {
            List<String> dateList = DateUtil.getMonday(date1,date2);
            dto.setDateList(dateList);
            if (StringUtils.isBlank(dto.getCh())) {
                dto.setCh("0");
                list0 = rtuDao.queryReport4(dto);
                dto.setCh("1");
                list1 = rtuDao.queryReport4(dto);
            } else {
                if ("0".equals(dto.getCh())) {
                    list0 = rtuDao.queryReport4(dto);
                } else if ("1".equals(dto.getCh())) {
                    list1 = rtuDao.queryReport4(dto);
                }
            }
        }
        Map map = new HashedMap();
        map.put("list0",list0);
        map.put("list1",list1);
        return map;
    }
    /*
     * 计算公式Q=MB(H1-H2)e1.5 H1为数据库中查到的va值 
     * 张公岭水库自动放水水量（虹吸管siphon）参数：M=1.8 B=0.5 H2=0.110 deviceid=18000004 ch=0
     * 张公岭水库溢洪流量（溢洪道spillway）参数：M=2.42 B=6 H2=6.18 deviceid=18000008    ch=1
     */ 
    @Override  
    public Map<String, Object> querySiphon(QuerySiphonDto dto) {
        @SuppressWarnings("unchecked")
		Map<String, Object> map = new HashedMap();
        List<SiphonDto> list = new ArrayList<SiphonDto>();
        List<SiphonDto> list2 = new ArrayList<SiphonDto>();
       
        if (StringUtils.isNotBlank(dto.getDate())) {
            dto.setBeginTime(dto.getDate() + " 00:00:00");
            dto.setEndTime(dto.getDate() + " 23:59:59");
         }else
         {
        	 Date date=new Date();
        	 SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        	 String time=sDateFormat.format(date);
        	 dto.setBeginTime(time + " 00:00:00");
             dto.setEndTime(time + " 23:59:59");
             
         }
        
        if (StringUtils.isNotBlank(dto.getBeginHour())) {
        	dto.setBeginTime((dto.getBeginTime()).substring(0, 10) + " "+dto.getBeginHour()+":00:00");
    
        }
        if (StringUtils.isNotBlank(dto.getEndHour())) {
           	dto.setEndTime((dto.getEndTime()).substring(0, 10) + " "+dto.getEndHour()+":59:59");
        	
        }
        Integer count = 0;
        Double watersum = (double) 0;
        count = rtuDao.countSiphon(dto);
        
        if (count == 0) {
            map.put("totalPage",0);
            map.put("totalCount",0);

        } else {
        	int totalPage = (count % dto.getPageRowCount() == 0) ? count / dto.getPageRowCount(): count / dto.getPageRowCount() + 1;
            dto.setStart((dto.getPage() - 1) * dto.getPageRowCount());
            list = rtuDao.querySiphon(dto);
         
            for(SiphonDto li:list)
            {
            	String str =li.getVa();
            	Double myva = Double.parseDouble(str);
            	Double mb = 1.8*0.5;
            	myva -=0.110;
            		
        		if(myva > 0)
        		{
            		//流量 L/s 乘1000是米换算成升
        			double sttemp =(double)Math.ceil(1000*mb*Math.pow(myva, 1.5));
        			//每5分钟水量 单位立方米  		
        			double mptemp =(double)Math.ceil(5*60*mb*Math.pow(myva, 1.5));
        			//总水量
        			watersum += 5*60*mb*Math.pow(myva, 1.5);
        			li.setSt(String.valueOf(sttemp));
            		li.setMp(String.valueOf(mptemp));
        			list2.add(li);           		
        		}
        		
            }
            map.put("totalPage",totalPage);
            map.put("totalCount",count);
          
        }
        map.put("pageRowCount", dto.getPageRowCount());
        map.put("page",dto.getPage());
      
		//watersum =(double)Math.ceil(watersum*1000)/1000;
        watersum =(double)Math.ceil(watersum);
        map.put("watersum",watersum);
        map.put("list",list2);

        return map;
    }
    /*
     * 计算公式Q=MB(H1-H2)e1.5 H1为数据库中查到的va值 
     * 张公岭水库自动放水水量（虹吸管siphon）参数：M=1.8 B=0.5 H2=0.110 deviceid=18000004 ch=0
     * 张公岭水库溢洪流量（溢洪道spillway）参数：M=2.42 B=6 H2=6.18 deviceid=18000008    ch=1
     */ 
    @Override  
    public Map<String, Object> querySpillway(QuerySiphonDto dto) {
        @SuppressWarnings("unchecked")
		Map<String, Object> map = new HashedMap();
        List<SiphonDto> list = new ArrayList<SiphonDto>();
        List<SiphonDto> list2 = new ArrayList<SiphonDto>();
       
        if (StringUtils.isNotBlank(dto.getDate())) {
            dto.setBeginTime(dto.getDate() + " 00:00:00");
            dto.setEndTime(dto.getDate() + " 23:59:59");
         }else
         {
        	 Date date=new Date();
        	 SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        	 String time=sDateFormat.format(date);
        	 dto.setBeginTime(time + " 00:00:00");
             dto.setEndTime(time + " 23:59:59");
             
         }
        
        if (StringUtils.isNotBlank(dto.getBeginHour())) {
        	dto.setBeginTime((dto.getBeginTime()).substring(0, 10) + " "+dto.getBeginHour()+":00:00");
    
        }
        if (StringUtils.isNotBlank(dto.getEndHour())) {
           	dto.setEndTime((dto.getEndTime()).substring(0, 10) + " "+dto.getEndHour()+":59:59");
        	
        }
        Integer count = 0;
        Double watersum = (double) 0;
        count = rtuDao.countSpillway(dto);
        
        if (count == 0) {
            map.put("totalPage",0);
            map.put("totalCount",0);

        } else {
           
        	int totalPage = (count % dto.getPageRowCount() == 0) ? count / dto.getPageRowCount() : count / dto.getPageRowCount() + 1;
            dto.setStart((dto.getPage() - 1) * dto.getPageRowCount());
            list = rtuDao.querySpillway(dto);
         
            for(SiphonDto li:list)
            {
            	String str =li.getVa();
            	Double myva = Double.parseDouble(str);
            	Double mb = 2.42*6;
            	myva -=6.18;
            	
        		if(myva > 0)
        		{
            		//流量 L/s 乘1000是米换算成升
        			double sttemp =(double)Math.ceil(1000*mb*Math.pow(myva, 1.5));
        			//每5分钟水量 单位立方米  		
        			double mptemp =(double)Math.ceil(5*60*mb*Math.pow(myva, 1.5));
        			//总水量
        			watersum += 5*60*mb*Math.pow(myva, 1.5);
        			li.setSt(String.valueOf(sttemp));
            		li.setMp(String.valueOf(mptemp));
        			list2.add(li);           		
        		}
        		
            }
            map.put("totalPage",totalPage);
            map.put("totalCount",count);
          
        }
        map.put("pageRowCount", dto.getPageRowCount());
        map.put("page",dto.getPage());
      
		watersum =(double)Math.ceil(watersum);
        map.put("watersum",watersum);
        map.put("list",list2);

        return map;
    }
    /*
     * 计算公式Q=MB(H1-H2)e1.5 H1为数据库中查到的va值 
     * 张公岭水库自动放水水量（虹吸管siphon）参数：M=1.8 B=0.5 H2=0.110 deviceid=18000004 ch=1
     * 张公岭水库溢洪流量（溢洪道spillway）参数：M=2.42 B=6 H2=6.18 deviceid=18000008 ch=1
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override  
    public Map queryYearSiphon(QuerySiphonDto dto) {
        Map<String, Object> map = new HashedMap();
        List<YearSiphonDto> list = new ArrayList<YearSiphonDto>();
        List<YearSiphonDto> list2 = new ArrayList<YearSiphonDto>();
       
        if (StringUtils.isNotBlank(dto.getYear())) {
            dto.setBeginTime(dto.getYear()+"-01-01 00:00:00");
         }
       
        if (StringUtils.isNotBlank(dto.getYear())) {           
            dto.setEndTime(dto.getYear()+"-12-31 23:59:59");
        }
        //年总水量
        Double watersum = (double) 0;
        Integer count = 0;
        Double mb = 0.0; 
        
        if(dto.getDeviceId() =="18000004") {
        	count = rtuDao.countSiphon(dto);
        	mb=1.8*0.5;
    	}
        
        if (count == 0) {
            map.put("totalPage",0);
            map.put("totalCount",0);
        } else {
            int totalPage = (count % dto.getPageRowCount() == 0) ? count / dto.getPageRowCount() : count / dto.getPageRowCount() + 1;
            dto.setStart((dto.getPage() - 1) * dto.getPageRowCount());
            list = rtuDao.queryYearSiphon(dto);

            for(YearSiphonDto li:list)
            {
            	String str =li.getVa();
            	double myva = Double.parseDouble(str);
            	
            	if(myva > 0)
            	{
            		Double daywater = mb*myva*60*5; 
            		watersum += daywater;
            		daywater =(double)Math.ceil(daywater);
           			li.setVa(String.valueOf(daywater));
            	    list2.add(li);  
            	}     	
            }
            map.put("totalPage",totalPage);
            map.put("totalCount",count);
        }
       
        map.put("pageRowCount", dto.getPageRowCount());
        map.put("page",dto.getPage());
        //一年的总水量
        watersum =(double)Math.ceil(watersum);
        map.put("watersum",watersum);
        map.put("list",list2);
     
    
        return map;
    }
    /*
     * 计算公式Q=MB(H1-H2)e1.5 H1为数据库中查到的va值 
     * 张公岭水库自动放水水量（虹吸管siphon）参数：M=1.8 B=0.5 H2=0.110 deviceid=18000004 ch=1
     * 张公岭水库溢洪流量（溢洪道spillway）参数：M=2.42 B=6 H2=6.18 deviceid=18000008 ch=1
     */
    @SuppressWarnings({ "rawtypes", "unchecked" })
	@Override  
    public Map queryYearSpillway(QuerySiphonDto dto) {
        Map<String, Object> map = new HashedMap();
        List<YearSiphonDto> list = new ArrayList<YearSiphonDto>();
        List<YearSiphonDto> list2 = new ArrayList<YearSiphonDto>();
       
        if (StringUtils.isNotBlank(dto.getYear())) {
            dto.setBeginTime(dto.getYear()+"-01-01 00:00:00");
         }       
        if (StringUtils.isNotBlank(dto.getYear())) {           
            dto.setEndTime(dto.getYear()+"-12-31 23:59:59");
        }
        
        //年总水量
        Double watersum = (double) 0;
        Integer count = 0;
        Double mb = 0.0;
       
        if (dto.getDeviceId() =="18000008") {
    		count = rtuDao.countSpillway(dto);
    		mb=2.42*6;
    	}
        
        if (count == 0) {
            map.put("totalPage",0);
            map.put("totalCount",0);
        } else {
            int totalPage = (count % dto.getPageRowCount() == 0) ? count / dto.getPageRowCount() : count / dto.getPageRowCount() + 1;
            dto.setStart((dto.getPage() - 1) * dto.getPageRowCount());
            list = rtuDao.queryYearSpillway(dto);
            for(YearSiphonDto li:list)
            {
            	String str =li.getVa();
            	double myva = Double.parseDouble(str);
            	
            	if(myva > 0)
            	{			        		
        			//一天的总水量
            		Double daywater = mb*myva*60*5; 
            		 
            		watersum += daywater;
        			daywater =(double)Math.ceil(daywater);
            		
           			li.setVa(String.valueOf(daywater));
            	    list2.add(li);  
            	}    	
            }
                 
            map.put("totalPage",totalPage);
            map.put("totalCount",count);
        }
        map.put("pageRowCount", dto.getPageRowCount());
        map.put("page",dto.getPage());
        //一年的总水量
        watersum =(double)Math.ceil(watersum);
        map.put("watersum",watersum);
        map.put("list",list2);
    
        return map;
    }
    /*
       public Map queryYearSiphon(QuerySiphonDto dto) {
        Map<String, Object> map = new HashedMap();
        List<YearSiphonDto> list = new ArrayList<YearSiphonDto>();
        List<YearSiphonDto> list2 = new ArrayList<YearSiphonDto>();
       
        if (StringUtils.isNotBlank(dto.getYear())) {
            dto.setBeginTime(dto.getYear()+"-01-01 00:00:00");
         }
       
        if (StringUtils.isNotBlank(dto.getYear())) {           
            dto.setEndTime(dto.getYear()+"-12-31 23:59:59");
        }
        
        Integer count = 0;
        if(dto.getDeviceId() =="18000004") {
        	count = rtuDao.countSiphon(dto);
    	}
    	else if (dto.getDeviceId() =="18000008") {
    		count = rtuDao.countSpillway(dto);
    	}
        //年总水量
        Double watersum = (double) 0;
        if (count == 0) {
            map.put("totalPage",0);
            map.put("totalCount",0);

        } else {
            int totalPage = (count % dto.getPageRowCount() == 0) ? count / dto.getPageRowCount() : count / dto.getPageRowCount() + 1;
            dto.setStart((dto.getPage() - 1) * dto.getPageRowCount());
            list = rtuDao.queryYearSiphon(dto);
           
            for(YearSiphonDto li:list)
            {
            	Integer month = Integer.parseInt(li.getTriggerDay().substring(5, 7));
                Integer day = Integer.parseInt(li.getTriggerDay().substring(8, 10));
                
            	String str =li.getVa();
            	double myva = Double.parseDouble(str);
            	Double mb = 0.0;
            	if(dto.getDeviceId() =="18000004") {
            		myva -=0.110;
            		mb=1.8*0.5;
            	}
            	else if (dto.getDeviceId() =="18000008") {
            		myva -=6.18;
            		mb=2.42*6;
            	}
            	if(myva > 0)
            	{
        			Double daywater = 24*60*60*mb*Math.pow(myva, 1.5);  			
            		watersum += daywater;
        			//一天的总水量
        			daywater =(double)Math.ceil(daywater*1000)/1000;
        			
        			li.setVa(String.valueOf(daywater));
            	    list2.add(li);  
            	}
            	
            }
            map.put("totalPage",totalPage);
            map.put("totalCount",count);
        }
        map.put("pageRowCount", dto.getPageRowCount());
        map.put("page",dto.getPage());
        //一年的总水量
        watersum =(double)Math.ceil(watersum*1000)/1000;
        map.put("watersum",watersum);
        map.put("list",list2);
    
        return map;
    }
    */
  
    public static void main(String[] args) {
    	SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd");
        try {
            Date date1 =sDateFormat.parse("2018-09-01");
            Date date2 =sDateFormat.parse("2018-12-01");
        	List<String> dateList = DateUtil.getMonday(date1,date2);
        	System.out.println(dateList.size());
        } catch(ParseException px) {
            px.printStackTrace();
        }

	}
}
